package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import ModelLayer.Supplier;

public class DBSupplier implements IFDBSupplier{
	
	 private  Connection con;
	    /** Creates a new instance of DBEmployee */
	    public DBSupplier() {
	      con = DbConnection1.getInstance().getDBcon();
	    }


	public ArrayList<Supplier> getAllSuppliers(boolean retriveAssociation) {
		//Auto-generated method stub
		 return miscWhere("", retriveAssociation);
	}

	public Supplier findSupplier(int supId) {
		// Auto-generated method stub
		String wClause = "  supplierID = '" + supId + "'";
        return singleWhere(wClause);
	}

	public Supplier searchSupplierName(String name) {
		// Auto-generated method stub
        String wClause = "supname like '%" + name + "%'";
        System.out.println("SearchSupplier " + wClause);
        return singleWhere(wClause);
	}

	public Supplier searchSupId(int supId) {
		// Auto-generated method stub
		String wClause = "supplierID = '" + supId + "'";
        System.out.println("Search Supplier: " + wClause);
        return singleWhere(wClause);
	}

	public int insertSupplier(Supplier sup) throws Exception {
		// Auto-generated method stub
		//call to get the next ID number
        int nextID = GetMax.getMaxId("Select max(supplierID) from supplier");
        nextID = nextID + 1;
        System.out.println("next supplierID = " +  nextID);
  
       int rc = -1;
	   String query="INSERT INTO supplier(supplierID, supname, supaddress, supzip, supPhoneNo, supEmail)  VALUES('"+
	  		nextID + "','" +
			sup.getName()  + "','"  +
		    sup.getAddress()  + "','"  +
		    sup.getZipCode()  + "','"  +
		    sup.getPhoneNumber()  + "','"  +
            sup.getEmail() + "')";
                     

       System.out.println("insert : " + query);
      try{ // insert new supplier +  dependent
          Statement stmt = con.createStatement();
          stmt.setQueryTimeout(5);
     	  rc = stmt.executeUpdate(query);
          stmt.close();
      }//end try
       catch(SQLException ex){
          System.out.println("Supplier ikke oprettet");
          throw new Exception ("Supplier is not inserted correct");
       }
       return(rc);
	}

	@Override
	public int updateSupplier(Supplier sup) {
		// TODO Auto-generated method stub
		Supplier supObj  = sup;
		int rc=-1;

		String query="UPDATE supplier SET "+
		 	  "supName ='"+ supObj.getName()+"', "+
		 	  "supAddress ='"+ supObj.getAddress() + "', " +
                          "supZip ='"+ supObj.getZipCode() + "', " +
                          "supPhoneNo ='"+ supObj.getPhoneNumber() + "', " +
                          "supEmail ='"+ supObj.getEmail() + "' " +
		          " WHERE supplierID = '"+ supObj.getSupplierId() + "'";
                System.out.println("Update query:" + query);
  		try{ // update Supplier
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	 	rc = stmt.executeUpdate(query);

	 	 	stmt.close();
		}//slut try
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in Supplier db: "+ex);
	  	}
		return(rc);
	}

	@Override
	public int deleteSupplier(int supID) {
		// TODO Auto-generated method stub
		int rc=-1;
		  
	  	String query="DELETE FROM supplier WHERE SupplierID = '" +
				supID + "'";
                System.out.println(query);
	  	try{ // delete from supplier
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	rc = stmt.executeUpdate(query);
	 	  	stmt.close();
  		}//slut try	
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in supplier db: "+ex);
   	        }
		return(rc);
	}
	
	private Supplier singleWhere(String wClause)
    {	
        ResultSet results;
        Supplier supObj = new Supplier();
        String query =  buildQuery(wClause);
        System.out.println("DbSupplier -singleWhere " + query); 
        try{ // read from project
        	Statement stmt = con.createStatement();
        	stmt.setQueryTimeout(5);
        	results = stmt.executeQuery(query);

	   if( results.next() ){
	       supObj = buildSupplier(results);
               //missing the test on retriveassociation
               
           }//end if
	   stmt.close();
	}//slut try	
	catch(Exception e){
	   System.out.println("Query exception - select employee : "+e);
	   e.printStackTrace();
        }
	return supObj;

    
    }
	
	 //miscWhere is used when more than one laaner is selected and build
    private ArrayList<Supplier> miscWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		ArrayList<Supplier> list = new ArrayList<Supplier>();
		
		String query =  buildQuery(wClause);
                System.out.println("DbSupplier " + query); 
  		try{ // read from project
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 	
			while( results.next() ){
		     	 Supplier supObj = new Supplier();
			 supObj = buildSupplier(results);	
                         list.add(supObj);
                         //missing tes on retriveAssociation
			}//end while
			stmt.close();
			
		}//slut try	
	 	catch(Exception e){
	 		System.out.println("Query exception - select supplier : "+e);
			e.printStackTrace();
	 	}
		return list;
	}
    
    private Supplier buildSupplier(ResultSet results)
    {
       Supplier supObj = new Supplier();
       
         try{
               supObj.setSupplierId(results.getInt("supplierID"));
               supObj.setName(results.getString("supname"));
               supObj.setAddress(results.getString("supAddress"));
               supObj.setZipCode(results.getString("supZip"));
               supObj.setCity(results.getString("city"));
               supObj.setCountry(results.getString("country"));
               supObj.setPhoneNumber(results.getString("supPhoneNo"));
               supObj.setEmail(results.getString("supEmail"));
               
          }
         catch(Exception e)
         {
             System.out.println("building supplier object");
         }
        
        return supObj;
        
    }
    
    private String buildQuery(String wClause)
	{
            String query="SELECT supplierID, supName, supAddress, supZip, city, country, supPhoneNo, supEmail FROM Supplier,zipcode where supZip=ZipCode"; 
            
           

		if (wClause.length()>0)
			query = query + "  and " + wClause;
			
		return query;
	}

}
